package com.zxshhy.aop;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Aspect
@Component
public class RequestTimeAspect {
    // 定义切点
    @Pointcut("execution(* com.zxshhy.controller.*.*(..))")
    public void serviceMethods() {}

    // 定义环绕通知
    @Around("serviceMethods()")
    public Object reqTimeAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String reqMethodNameUrl = request.getRequestURI();
        log.info("【{}】接口请求开始时间：{}",reqMethodNameUrl,startTime);
        Object proceed = proceedingJoinPoint.proceed();
        log.info("【{}】接口请求结束,总耗时:{} ms，返回结果:{}", reqMethodNameUrl,System.currentTimeMillis() - startTime,JSONObject.toJSONString(proceed));
        return proceed;
    }

    // 定义后置通知
    @AfterReturning("serviceMethods()")
    public void AfterReturning(JoinPoint joinPoint) {
        log.info("AfterReturning: {}",joinPoint.getSignature());
    }

}
